package com.dmz.wxcp.wecom.signature.controller;

import com.dmz.wxcp.constants.Constant;
import com.dmz.wxcp.redis.RedisUtils;
import com.dmz.wxcp.wecom.common.service.RedisService;
import lombok.AllArgsConstructor;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * @author Edward
 */
@AllArgsConstructor
@Controller
@RequestMapping("/wx/redirect/{appid}")
public class WxRedirectController {
    private final WxMpService wxService;

    @Autowired
    private RedisService redisService;

    @RequestMapping("/greet")
    public String greetUser(@PathVariable String appid, @RequestParam String code, ModelMap map, HttpServletRequest request) {
        String accesstokenkey= Constant.USERINFO_ACCESSTOKEN;
        if (!this.wxService.switchover(appid)) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", appid));
        }
        try {
//            首先在Redis中查找是否有token
            WxOAuth2AccessToken accessToken=new WxOAuth2AccessToken();
            if (redisService.hasKey(accesstokenkey)) {
                accessToken= RedisUtils.RedisToObject((String)redisService.get(accesstokenkey),WxOAuth2AccessToken.class);
                if (!wxService.getOAuth2Service().validateAccessToken(accessToken)) {
                     accessToken = wxService.getOAuth2Service().getAccessToken(code);
                     redisService.set(accesstokenkey,accessToken,3600, TimeUnit.SECONDS);
                }
            }else{
                accessToken = wxService.getOAuth2Service().getAccessToken(code);
                redisService.set(accesstokenkey,accessToken,3600, TimeUnit.SECONDS);
            }
            WxOAuth2UserInfo user = wxService.getOAuth2Service().getUserInfo(accessToken, null);
            request.getSession().setAttribute("openid",user.getOpenid());
            map.put("user",user);
        } catch (WxErrorException e) {
            e.printStackTrace();
        }

        return "greetuser";
    }
}
